package com.tange.ai.core.sample.home

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import android.view.*
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.PopupMenu
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.tange.ai.core.sample.R
import com.tange.ai.core.sample.assistance.DevelopmentAssistanceActivity
import com.tange.ai.core.sample.binding.BindingWaysActivity
import com.tange.ai.core.sample.databinding.ActivityHomeBinding
import com.tange.ai.core.sample.firmware.FirmwareUpgradeActivity
import com.tange.ai.core.sample.message.MessageListActivity
import com.tange.ai.core.sample.play.DeviceLiveActivity
import com.tange.ai.core.sample.share.DeviceShareActivity
import com.tange.ai.core.sample.token.InternalAccountLoginActivity
import com.tange.base.toolkit.*
import com.tange.base.ui.design.BasicDialogInput
import com.tange.base.ui.design.BasicDialogLoading
import com.tange.base.ui.design.BasicDialogRequest
import com.tange.core.access.token.Authentication
import com.tange.core.builtin.account.BuiltinAccount
import com.tange.core.device.manage.DeviceInfoBasic
import com.tange.core.device.manage.DeviceInfoQuery
import com.tange.core.device.manage.DeviceOnlineStatus
import com.tange.core.device.manage.DeviceThumbnail
import com.tange.core.sharing.DeviceSharing
import com.tg.appcommon.android.TGLog

class HomeActivity : AppCompatActivity() {

    companion object {
        const val TAG = "HomeActivity_"
        private const val VIEW_TYPE_DEVICE = 0
        private const val VIEW_TYPE_MORE = 1
        private const val PAGE_LIMIT = 10
    }

    private lateinit var binding: ActivityHomeBinding

    private lateinit var listAdapter: ListAdapter

    private val devices = ArrayList<Device>()

    private var loading: BasicDialogLoading? = null

    private var bindingPrepareRemind = false

    data class Device(
        var deviceInfoBasic: DeviceInfoBasic? = null,
        var deviceOnlineStatus: DeviceOnlineStatus? = null,
        var deviceThumbnail: DeviceThumbnail? = null
    )

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        StatusBarUtil.setLightStatusBar(this, true)
        StatusNavUtils.setStatusBarColor(this, ContextCompat.getColor(this, R.color.app_background))
        requestWindowFeature(Window.FEATURE_NO_TITLE)
        binding = ActivityHomeBinding.inflate(layoutInflater).apply {
            setContentView(root)
            supportActionBar?.hide()
            root.paddingStatusBar()
        }

        binding.swipeRefresh.apply {
            setProgressBackgroundColorSchemeColor(ContextCompat.getColor(this@HomeActivity, R.color.basic_color_brand_0))
            setColorSchemeColors(Color.WHITE)
            setOnRefreshListener {
                devices.clear()
                requireDeviceList()
            }
        }

        listAdapter = ListAdapter()
        binding.apList.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        binding.apList.adapter = listAdapter

        loading = BasicDialogLoading(this).apply {
            setMessage("刷新中...")
        }

        binding.add.onClicked {
            val menu = PopupMenu(it.context, it)
            menu.inflate(R.menu.menu_add_device)
            menu.setOnMenuItemClickListener {
                if (it.itemId == R.id.from_device_binding) {
                    binding()
                    true
                } else if (it.itemId == R.id.from_share_code) {
                    recognizeShareCode()
                    true
                }
                false
            }
            menu.gravity = Gravity.END
            menu.show()
        }

        binding.retry.onClicked {
            requireDeviceList()
        }

        binding.help.onClicked {
            startActivity(Intent(this@HomeActivity, DevelopmentAssistanceActivity::class.java))
        }

        binding.logout.onClicked {
            logout()
        }
    }

    private fun recognizeShareCode() {

        val shareCode = ClipboardUtils.paste(this)
        if (TextUtils.isEmpty(shareCode) || !shareCode.startsWith("SC://")) {
            Tips.show("剪贴板无分享码！")
            return
        }

        DeviceSharing.queryCode(shareCode) {
            if (it.success) {

                it.data?.let {

                    val owner = if (!TextUtils.isEmpty(it.ownerNickName)) it.ownerNickName else "${it.ownerUserId}"
                    val deviceName = if ((it.deviceName?.size ?: 0) > 0) it.deviceName?.get(0) else "未知设备"

                    BasicDialogRequest(this@HomeActivity).apply {
                        setMessage("来自${owner}的\"${deviceName}\"，是否接受？")
                        setPositiveText("收下")
                        setNegativeText("不要了")
                        setPositiveOnClicked {


                            DeviceSharing.acceptCode(shareCode) {
                                if (it.success) {
                                    Tips.show("接收成功！")
                                    requireDeviceList()
                                } else {
                                    Tips.show("接收失败 ${it.message}")
                                }
                            }

                        }
                    }.show()

                }

            } else {
                Tips.show("分享码识别失败：${it.code} ${it.message}")
            }
        }
    }

    private fun binding() {
        if (bindingPrepareRemind) {
            startActivity(Intent(this@HomeActivity, BindingWaysActivity::class.java))
        } else {
            BasicDialogRequest(this@HomeActivity).apply {
                setMessage("请让设备进入\"配网模式\"后，再点击下一步")
                setPositiveText("下一步")
                setPositiveOnClicked {
                    bindingPrepareRemind = true
                    startActivity(Intent(this@HomeActivity, BindingWaysActivity::class.java))
                    dismiss()
                }
            }.show()
        }
    }

    private fun logout() {
        BasicDialogRequest(this@HomeActivity).apply {
            setMessage("确定要退出登录吗？")
            setPositiveText("是的")
            setPositiveOnClicked {
                dismiss()
                BuiltinAccount.login().logout {
                    if (!it.success) Tips.show("注销失败：${it.code}, ${it.message}")
                    else Tips.show("用户令牌已成功注销")

                    PreferenceUtil.setStringCommit(this@HomeActivity,
                        InternalAccountLoginActivity.PRE_USER_NAME,
                        "")
                    PreferenceUtil.setStringCommit(this@HomeActivity,
                        InternalAccountLoginActivity.PRE_USER_PWD,
                        "")
                    Authentication.clear()
                    finish()
                }
            }
            setNegativeText("算了")
            setNegativeOnClicked {
                dismiss()
            }
        }.show()
    }

    override fun onResume() {
        super.onResume()

        binding.swipeRefresh.isRefreshing = true
        devices.clear()
        requireDeviceList()
    }

    private fun requireDeviceList() {
        binding.emptyView.gone()

        DeviceInfoQuery.requireBasic(devices.size, PAGE_LIMIT) {
            loading?.dismiss()
            binding.swipeRefresh.isRefreshing = false
            if (it.success) {
                if ((it.data?.list?.size ?: 0) > 0) {
                    it.data?.list?.forEach { devices.add(Device(deviceInfoBasic = it)) }
                    it.data?.list?.let { requireDeviceOnlineStatus(it) }
                } else {
                    if (devices.size == 0) {
                        binding.emptyView.visible()
                        binding.apList.gone()
                    } else {
                        Tips.show("没有更多数据了")
                    }
                }
            } else {
                Tips.show("请求出错 ${it.code}, ${it.message}")
                if (devices.size == 0) {
                    binding.emptyView.visible()
                    binding.apList.gone()
                }
            }
        }
    }

    private fun requireDeviceOnlineStatus(deviceList: List<DeviceInfoBasic>) {
        val list = ArrayList<String>().apply {
            deviceList.forEach { it.deviceId?.let { add(it) } }
        }

        DeviceInfoQuery.requireOnlineStatus(list) {
            if (it.success) {
                if ((it.data?.size ?: 0) > 0) {

                    devices.forEach { device ->
                        val key = device.deviceInfoBasic?.deviceId ?: ""
                        if (it.data?.containsKey(key) == true) {
                            device.deviceOnlineStatus = it.data?.get(key)
                        }
                    }

                    requireDeviceThumbnail(deviceList)
                }


            } else {
                Tips.show("请求出错 ${it.code}, ${it.message}")
                loading?.dismiss()
                binding.emptyView.visible()
                binding.apList.gone()
            }
        }
    }

    private fun requireDeviceThumbnail(deviceList: List<DeviceInfoBasic>) {
        val list = ArrayList<String>().apply {
            deviceList.forEach { it.deviceId?.let { add(it) } }
        }

        DeviceInfoQuery.requireThumbnail(list) {
            if (it.success) {
                if ((it.data?.size ?: 0) > 0) {

                    devices.forEach { device ->
                        val key = device.deviceInfoBasic?.deviceId ?: ""
                        if (it.data?.containsKey(key) == true) {
                            device.deviceThumbnail = it.data?.get(key)
                        }
                    }

                    TGLog.i(TAG, "[requireDeviceThumbnail] devices = $devices")

                    listAdapter.refresh(devices)
                    loading?.dismiss()
                    binding.emptyView.gone()
                    binding.apList.visible()
                }


            } else {
                Tips.show("请求出错 ${it.code}, ${it.message}")
                loading?.dismiss()
                binding.emptyView.visible()
                binding.apList.gone()
            }
        }
    }


    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean =
        if (KeyEvent.KEYCODE_BACK == keyCode) true else super.onKeyDown(keyCode, event)


    inner class ListAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
        private val deviceList: MutableList<Device> = ArrayList()
        fun refresh(list: List<Device>) {
            deviceList.clear()
            deviceList.addAll(list)
            notifyDataSetChanged()
        }

        override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
            return if (viewType == VIEW_TYPE_DEVICE) {
                val view: View = LayoutInflater.from(viewGroup.context)
                    .inflate(R.layout.item_device_list, viewGroup, false)
                ViewHolderDevice(view)
            } else {
                val view: View = LayoutInflater.from(viewGroup.context)
                    .inflate(R.layout.item_message_load_more, viewGroup, false)
                ViewHolderLoadMore(view)
            }
        }

        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
            if (holder is ViewHolderDevice) {
                val viewHolderDevice: ViewHolderDevice = holder
                val item = deviceList[position]
                viewHolderDevice.name.text = item.deviceInfoBasic?.deviceName ?: ""

                val isOwner = item.deviceInfoBasic?.isOwner == true

                if (isOwner) {
                    viewHolderDevice.shareLabel.gone()
                    viewHolderDevice.upgrade.visible()
                    viewHolderDevice.share.visible()
                } else {
                    viewHolderDevice.shareLabel.visible()
                    viewHolderDevice.upgrade.gone()
                    viewHolderDevice.share.gone()
                }


                val online = item.deviceOnlineStatus?.isOnline == true
                val deviceId = item.deviceInfoBasic?.deviceId ?: ""
                viewHolderDevice.offline.visibility = if (online) View.GONE else View.VISIBLE

                item.deviceThumbnail?.url?.let {
                    Glide.with(this@HomeActivity).load(it).error(R.drawable.light_gray_rounded_bg)
                        .apply(RequestOptions.bitmapTransform(RoundedCorners(25))).into(viewHolderDevice.cover)
                }

                viewHolderDevice.message.setOnClickListener {
                    MessageListActivity.launch(this@HomeActivity, deviceId)
                }

                viewHolderDevice.upgrade.setOnClickListener {
                    FirmwareUpgradeActivity.launch(it.context, deviceId)
                }

                viewHolderDevice.share.setOnClickListener {
                    DeviceShareActivity.launch(it.context, deviceId)
                }

                viewHolderDevice.itemView.setOnClickListener { view: View? ->
                    if (online) {
                        DeviceLiveActivity.launch(this@HomeActivity, deviceId)
                    } else {
                        Tips.show("设备不在线呢！")
                    }
                }
            } else if (holder is ViewHolderLoadMore) {
                holder.itemView.setOnClickListener {
                    loading?.dismiss()
                    loading?.show()
                    requireDeviceList()
                }
            }
        }

        override fun getItemCount(): Int {
            return if (deviceList.size == 0) 0
            else deviceList.size + 1
        }

        override fun getItemViewType(position: Int): Int = if (position == (itemCount - 1)) VIEW_TYPE_MORE else VIEW_TYPE_DEVICE
    }

    class ViewHolderDevice(view: View) : RecyclerView.ViewHolder(view) {
        val cover: ImageView
        val message: ImageView
        val upgrade: ImageView
        val name: TextView
        val offline: TextView
        val shareLabel: TextView
        val share: ImageView

        init {
            share = view.findViewById(R.id.share)
            shareLabel = view.findViewById(R.id.share_label)
            cover = view.findViewById(R.id.cover)
            message = view.findViewById(R.id.message)
            upgrade = view.findViewById(R.id.upgrade)
            name = view.findViewById(R.id.name)
            offline = view.findViewById(R.id.offline_tips)
        }
    }

    class ViewHolderLoadMore(view: View) : RecyclerView.ViewHolder(view)
}